package ua.khpi.si.kit49.diploma.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import ua.khpi.si.kit49.diploma.db.dto.City;
import ua.khpi.si.kit49.diploma.exception.WeatherException;
import ua.khpi.si.kit49.diploma.util.WeatherUtilit;

/**
 * Implementation of weather service
 * 
 * @author netstalk3r
 * 
 */

@Component("weatherService")
public class WeatherServiceImpl implements WeatherService {

	// request for weather
	private static final String REQUEST = "http://weather.yahooapis.com/forecastrss?u=c&w=";

	/**
	 * Logger
	 */
	private static final Logger log = Logger
			.getLogger(WeatherServiceImpl.class);

	// counter for threads
	private static volatile int count = 0;

	public static void reduceCount() {
		count--;
	}

	@Override
	public List<City> getWeatherForAllCities(final List<City> cities)
			throws Exception {
		log.info("Weather service - start.");
		try {
			for (int i = 0; i < cities.size(); i++) {
				Integer woeid = cities.get(i).getWoeid();
				new Thread(new WeatherUtilit(count++, REQUEST
						+ woeid.toString(), cities.get(i).getWeather()))
						.start();
			}
			while (count > 0) {
			}
			log.info("Weather service - finish.");
		} catch (Exception e) {
			log.error(e.getMessage());
			Exception exception = (Exception) e.getCause();
			throw new WeatherException(exception.getMessage());
		}
		return cities;
	}

}
